Skip to content

Java 发送 Email 并与 Spring 集成

使用 Jakarta Mail 发送邮件

2018 年 9 月 14 日,JavaMail 项目迁移至 Eclipse 基金会! 2019 年 7 月 3 日,JavaMail 的名称变更为 Jakarta Mail。

截止到 2020-07-18,最新版本为 Jakarta Mail 1.6.5。

在 Maven 项目中添加 Maven 依赖项:

xml
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>jakarta.mail</artifactId>
    <version>1.6.5</version>
</dependency>

发送简单的 Email

java
package study.helloworld;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

public class SimpleMailSend {
    public static void main(String[] args) {
        String from = "[email protected]"; // 发件人邮箱
        String to = "[email protected]"; // 收件人邮箱
        String subject = "Hello, World!"; // 主题
        String text = "你好,世界!"; // 文本内容
        String smtpHost = "smtp.qq.com"; // 发件人邮箱的 SMTP 服务器地址

        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);

        // 创建一个会话
        Session session = Session.getDefaultInstance(props);

        // 启用调试模式
        session.setDebug(true);

        // 创建一封邮件
        MimeMessage msg = new MimeMessage(session);
        try {
            // 设置发件人邮箱和发件人名称(可选)
            msg.setFrom(new InternetAddress(from, "大米公司"));

            // 设置收件人邮箱和收件人名称(可选)
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to, "米粉"));
            // 还可以设置抄送人和密送人
            msg.setRecipient(Message.RecipientType.CC, new InternetAddress("[email protected]"));
            msg.setRecipient(Message.RecipientType.BCC, new InternetAddress("[email protected]"));

            // 想要发送(抄送、密送)给多个人
//            msg.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(from, "米粉") });
//            msg.setRecipients(Message.RecipientType.CC, new InternetAddress[] { new InternetAddress("[email protected]") });
//            msg.setRecipients(Message.RecipientType.BCC, new InternetAddress[] { new InternetAddress("[email protected]") });

            // 设置主题
            msg.setSubject(subject);

            // 设置文本内容
            msg.setText(text);

            // 设置时间
            msg.setSentDate(new Date());

            // 根据指定协议获取传输对象
            Transport transport = session.getTransport("smtp");
            // 使用账号和密码连接
            transport.connect(from, "xxx");

            // 发送邮件(发送给所有的人)
            transport.sendMessage(msg, msg.getAllRecipients());

            // 关闭传输对象
            transport.close();

        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

发送带附件的 Email

java
package study.helloworld;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

public class AttachmentMailSend {
    public static void main(String[] args) {
        String from = "[email protected]"; // 发件人邮箱
        String to = "[email protected]"; // 收件人邮箱
        String subject = "Hello, World!"; // 主题
        String text = "你好,世界!"; // 文本内容
        String smtpHost = "smtp.qq.com"; // 发件人邮箱的 SMTP 服务器地址

        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);

        // 创建一个会话
        Session session = Session.getDefaultInstance(props);

        // 启用调试模式
        session.setDebug(true);

        // 创建一封邮件
        MimeMessage msg = new MimeMessage(session);
        try {
            // 设置发件人邮箱和发件人名称(可选)
            msg.setFrom(new InternetAddress(from, "大米公司"));

            // 设置收件人邮箱和收件人名称(可选)
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to, "米粉"));
            // 还可以设置抄送人和密送人
            msg.setRecipient(Message.RecipientType.CC, new InternetAddress("[email protected]"));
            msg.setRecipient(Message.RecipientType.BCC, new InternetAddress("[email protected]"));

            // 想要发送(抄送、密送)给多个人
//            msg.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(from, "米粉") });
//            msg.setRecipients(Message.RecipientType.CC, new InternetAddress[] { new InternetAddress("[email protected]") });
//            msg.setRecipients(Message.RecipientType.BCC, new InternetAddress[] { new InternetAddress("[email protected]") });

            // 设置主题
            msg.setSubject(subject);

            // 设置正文
            MimeBodyPart mainBodyPart = new MimeBodyPart();
            // 设置文本内容
            mainBodyPart.setText(text);

            // 还可以在正文中插入图片
            MimeBodyPart picBodyPart = new MimeBodyPart();
            picBodyPart.attachFile(new File("a.jpg"));

            MimeMultipart picMultipart = new MimeMultipart();
            picMultipart.addBodyPart(picBodyPart);

            mainBodyPart.setContent(picMultipart);

            // 设置附件
            MimeBodyPart attachBodyPart = new MimeBodyPart();
            attachBodyPart.attachFile(new File("大米公司财报.xlsx"));

            // 创建多部件对象
            MimeMultipart mimeMultipart = new MimeMultipart();
            mimeMultipart.addBodyPart(mainBodyPart);
            mimeMultipart.addBodyPart(attachBodyPart);

            // 设置邮件内容
            msg.setContent(mimeMultipart);

            // 设置时间
            msg.setSentDate(new Date());

            // 根据指定协议获取传输对象
            Transport transport = session.getTransport("smtp");
            // 使用账号和密码连接
            transport.connect(from, "xxx");

            // 发送邮件(发送给所有的人)
            transport.sendMessage(msg, msg.getAllRecipients());

            // 关闭传输对象
            transport.close();

        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Spring 集成 Java Mail

Spring Framework 为使用接口发送电子邮件提供了一个简单的抽象,Spring Boot 为它提供了自动配置以及启动器模块 JavaMailSender

在 SpringBoot 项目中添加 Maven 依赖项:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

在 application.properties 文件中配置:

properties
# 发件人邮箱的 SMTP 服务器地址
spring.mail.host=smtp.qq.com
# 发件人邮箱账号
spring.mail.username[email protected]
# 发件人邮箱密码
spring.mail.password=xxx

某些超时值默认为不超时,通常更改该值以避免线程被无响应的邮件服务器阻塞:

properties
# 邮件服务器超时时间
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000

使用 Spring Boot 发送简单的 Email

java
package study.helloworld.springjavamailsamples;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;

@Service
public class SimpleMailSendService {

    @Autowired
    private Environment environment;
    @Autowired
    private JavaMailSender javaMailSender;

    public void sendSimpleMail() {
        String from = environment.getRequiredProperty("spring.mail.username"); // 发件人邮箱
        String to = "[email protected]"; // 收件人邮箱
        String subject = "Hello, World!"; // 主题
        String text = "你好,世界!"; // 文本内容

        // 创建一封邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            // 设置发件人邮箱和发件人名称(可选)
            mimeMessage.setFrom(from);

            // 设置收件人邮箱和收件人名称(可选)
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to, "米粉"));

            // 还可以设置抄送人和密送人
            mimeMessage.setRecipient(Message.RecipientType.CC, new InternetAddress(to, "[email protected]"));
            mimeMessage.setRecipient(Message.RecipientType.BCC, new InternetAddress(to, "[email protected]"));

            // 想要发送(抄送、密送)给多个人
//            mimeMessage.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(from, "米粉") });
//            mimeMessage.setRecipients(Message.RecipientType.CC, new InternetAddress[] { new InternetAddress("[email protected]") });
//            mimeMessage.setRecipients(Message.RecipientType.BCC, new InternetAddress[] { new InternetAddress("[email protected]") });

            // 设置主题
            mimeMessage.setSubject(subject);

            // 设置文本内容
            mimeMessage.setText(text);

            // 设置时间
            mimeMessage.setSentDate(new Date());

            // 发送邮件(发送给所有的人)
            javaMailSender.send(mimeMessage);

        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

使用 Spring Boot 发送带附件的 Email

java
package study.helloworld.springjavamailsamples;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;

@Service
public class AttachmentMailSendService {

    @Autowired
    private Environment environment;
    @Autowired
    private JavaMailSender javaMailSender;

    public void sendAttachmentMail() {
        String from = environment.getRequiredProperty("spring.mail.username"); // 发件人邮箱
        String to = "[email protected]"; // 收件人邮箱
        String subject = "Hello, World!"; // 主题
        String text = "你好,世界!"; // 文本内容

        // 创建一封邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

            // 设置发件人邮箱和发件人名称(可选)
            mimeMessageHelper.setFrom(from);

            // 设置收件人邮箱和收件人名称(可选)
            mimeMessageHelper.setTo(new InternetAddress(to, "米粉"));

            // 还可以设置抄送人和密送人
            mimeMessageHelper.setCc(new InternetAddress(to, "[email protected]"));
            mimeMessageHelper.setBcc(new InternetAddress(to, "[email protected]"));

            // 想要发送(抄送、密送)给多个人
//            mimeMessageHelper.setTo(new InternetAddress[] { new InternetAddress(from, "米粉") });
//            mimeMessageHelper.setCc(new InternetAddress[] { new InternetAddress("[email protected]") });
//            mimeMessageHelper.setBcc(new InternetAddress[] { new InternetAddress("[email protected]") });

            // 设置主题
            mimeMessageHelper.setSubject(subject);

            // 设置文本内容
            mimeMessageHelper.setText(text);

            // 还可以在正文中插入图片
            mimeMessageHelper.addInline("", new File("a.jpg"));

            // 设置附件
            mimeMessageHelper.addAttachment("mi_report.xlsx", new File("大米公司财报.xlsx"));

            // 设置时间
            mimeMessageHelper.setSentDate(new Date());

            // 发送邮件(发送给所有的人)
            javaMailSender.send(mimeMessage);

        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

Released under the MIT License.